import { request } from "../../request/index.js";
import regeneratorRuntime from "../../libs/runtime/runtime";

Page({
    /**
     * 页面的初始数据
     */
    data: {
        addressList: {}, //收货地址的数据
        shoppingList: [], //商品详情
        shoppingList1: {},
        number: 1, //商品数量
        paytype: "", //支付方式
        postage: 0, //配送费
        totalPrices: "", //总价

        addressId: "", //地址的id
        couponId: "", // 优惠卷的id
        couponPrice: "", //优惠卷的价格
        hideview: false, //默认不显示
        pocketPrice: "", //实付金额
        orderNumber: "", //订单编号
        active: false,
        total: 0,
        shoppingPrice: 0,
        judge: false,
        show: false,
        radio: "1",
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {
        if (wx.getStorageSync("pitchData")) {
            let bb = wx.getStorageSync("pitchData");
            let total = 0;
            bb.forEach((item, index) => {
                this.setData({
                    total: this.data.total + item.price * item.count,
                });
                console.log(this.data.total);
            });
            let addressList = wx.getStorageSync("addressInfo");

            this.setData({
                active: false,
                totalPrices: this.data.total,
                shoppingList: bb,
                pocketPrice: this.data.total - wx.getStorageSync("couponPrice"), //赋值实付金额
                addressId: addressList.addressId, //赋值地址的id
            });
            console.log(this.data.addressId, "88888888");

            if (this.data.addressId) {
                this.postagePost(); //计算配送费
            }
        } else {
            this.setData({
                active: true,
            });
            this.shoppingPost();
        }
    },
    //商品详情数据
    async shoppingPost() {
        let res = await request({
            url: "Goods/findByGoodId",
            data: { goodsId: wx.getStorageSync("goodsId") },
        });
        console.log(res);

        if (res.code == 200) {
            res.data.count = this.data.number;
            this.setData({
                shoppingList1: res.data,
            });
            if (wx.getStorageSync("paytype") == "1") {
                this.setData({
                    totalPrices: res.data.price * this.data.number, //赋值总价用于获取可用优惠卷
                    pocketPrice: res.data.price * this.data.number -
                        wx.getStorageSync("couponPrice"), //赋值实付金额
                    shoppingPrice: res.data.price,
                    judge: false,
                });
            } else if (wx.getStorageSync("paytype") == "2") {
                this.setData({
                    totalPrices: res.data.vipPrice * this.data.number, //赋值总价用于获取可用优惠卷
                    pocketPrice: res.data.vipPrice * this.data.number -
                        wx.getStorageSync("couponPrice"), //赋值实付金额
                    shoppingPrice: res.data.vipPrice,
                    judge: false,
                });
            } else if (wx.getStorageSync("paytype") == "3") {
                this.setData({
                    totalPrices: res.data.discountsPrice * this.data.number, //赋值总价用于获取可用优惠卷
                    pocketPrice: res.data.discountsPrice * this.data.number -
                        wx.getStorageSync("couponPrice"), //赋值实付金额
                    shoppingPrice: res.data.discountsPrice,
                    judge: true,
                });
            }
            this.postagePost(); //计算配送费
        }
    },
    // 点击地址区域的按钮
    administration() {
        wx.navigateTo({
            url: "../address/address",
        });
    },
    //领取优惠卷
    preferential() {
        wx.navigateTo({
            url: "../couponCard/couponCard?price=" + this.data.pocketPrice,
        });
    },
    //计算配送费
    async postagePost() {
        let res = await request({
            url: "Address/shippingFee",
            data: {
                addressId: this.data.addressId, //地址的id
                price: this.data.totalPrices, //商品的总价
            },
        });
        if (res.code == 200) {
            this.setData({
                postage: res.data, //赋值配送费
                pocketPrice: this.data.pocketPrice + res.data,
            });
        }
    },
    //提交订单按钮
    async goOkOrder() {
        if (this.data.addressList == "") {
            wx.showToast({
                title: "请选择收货地址",
                icon: "none",
                image: "",
                duration: 1500,
            });
            return;
        }
        this.setData({
            show: true,
        });
    },
    //支付方式的change事件
    onChange(e) {
        console.log(e);
        this.setData({
            radio: e.detail,
        });
    },
    //关闭弹框
    onClose() {
        this.setData({
            show: false,
        });
    },
    //选择完支付方式后确定按钮
    async getUserInfo() {
        if (this.data.active) {
            //直接购买商品的接口

            let res = await request({
                url: "BlanketOrder/addOrder",
                data: {
                    payType: +this.data.paytype, //支付方式
                    goodId: wx.getStorageSync("goodsId"), //商品的id
                    count: this.data.number, //数量
                    couponId: wx.getStorageSync("couponId"), //优惠卷id
                    addressId: this.data.addressId, //地址的id
                },
            });
            console.log(res);
            if (res.code == 200) {
                this.setData({
                    orderNumber: res.data.orderNumber,
                });
                if (this.data.radio == "1") {
                    this.paymentPost();
                } else {
                    this.userInfoPost();
                }
            } else {
                wx.showToast({
                    title: res.msg,
                    icon: "none",
                });
            }
        } else {
            // 从购物车下单的接口;
            let cc = wx.getStorageSync("pitchData");
            let dd = [];
            cc.forEach((item, index) => {
                dd[index] = item.goodId;
            });
            let res = await request({
                url: "BlanketOrder/addShoppingOrder",
                data: {
                    goodIdList: dd, //商品的id
                    couponId: wx.getStorageSync("couponId"), //优惠卷id
                    addressId: this.data.addressId, //地址的id
                },
            });
            console.log(res, "555555555555");
            if (res.code == 200) {
                this.setData({
                    orderNumber: res.data.orderNumber,
                });
                if (this.data.radio == "1") {
                    this.paymentPost();
                } else {
                    this.userInfoPost();
                }
            } else {
                wx.showToast({
                    title: res.msg,
                    icon: "none",
                });
            }
        }
    },
    //获取用户的信息,比较用户余额
    async userInfoPost() {
        let res = await request({
            url: "User/findById",
        });
        if (this.data.pocketPrice > res.data.money) {
            wx.showToast({
                title: "用户余额不足,请充值!",
                icon: "none",
                duration: 2000,
            });
            console.log("没有执行");
            return;
        } else {
            console.log(res, "执行了");
            this.balancePayment(); //余额支付
        }
    },
    //余额支付
    async balancePayment() {
        let res = await request({
            url: "BlanketOrder/balancePay",
            data: { orderNumber: this.data.orderNumber },
        });
        console.log(res, "余额支付");
        if (res.code == 200) {
            wx.showToast({
                title: "支付成功",
                image: "",
                duration: 1500,
            });
            setTimeout(() => {
                wx.switchTab({
                    url: "../myName/index",
                });
            }, 2000);
        } else {
            wx.showToast({
                title: res.msg,
                icon: "none",
            });
        }
    },
    // 支付接口
    async paymentPost() {
        let res = await request({
            url: "pay/wx/toPay",
            data: { orderNumber: this.data.orderNumber },
        });
        console.log(res);
        if (res.code == 200) {
            let aa = res.data.timeStamp + "";
            wx.requestPayment({
                timeStamp: aa, //时间戳
                nonceStr: res.data.nonceStr, //随机字符串
                package: res.data.package, //统一下单接口返回的 prepay_id 参数值
                signType: res.data.signType, //签名算法
                paySign: res.data.sign, //签名
                success: function(res) {
                    wx.showToast({
                        title: "支付成功",
                        image: "",
                        duration: 1500,
                    });
                    setTimeout(() => {
                        wx.switchTab({
                            url: "../myName/index",
                        });
                    }, 2000);

                },
                fail: function(err) {
                    wx.showToast({
                        title: "支付失败",
                        icon: "none",
                        image: "",
                        duration: 1500,
                    });
                    setTimeout(() => {
                        wx.switchTab({
                            url: "../myName/index",
                        });
                    }, 2000);
                },
            });
        } else {
            wx.showToast({
                title: res.msg,
                icon: "none",
            });
        }
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function() {},

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function() {
        let addressList = wx.getStorageSync("addressInfo");

        this.setData({
            addressList: addressList, //赋值收货地址的信息
            addressId: addressList.addressId, //赋值地址的id
            number: wx.getStorageSync("count"),
            paytype: wx.getStorageSync("paytype"),
            couponId: wx.getStorageSync("couponId"),
            couponPrice: wx.getStorageSync("couponPrice") || 0, //如果没有优惠卷的话那就是 0
        });

        // this.defaultAddress();
        if (this.data.couponPrice != "") {
            this.setData({
                hideview: true,
            });
        }
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function() {},

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function() {},

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function() {},

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function() {},

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function() {},
});